<?php
	require_once(dirname(__FILE__) . "/assert.php");
	$allowedInaccurateFactor = 0.01;
	
	$expectedWidth = $_GET["width"];
	$expectedHeight = $_GET["height"];
	
	$path = dirname(__FILE__) . '/../uploads';
	$URI = $path . '/' . getMostRecentPdfFile($path);
	//echo $URI;
	
	$output = shell_exec("pdfinfo ".$URI);
	// find page count
	preg_match('/Pages:\s+([0-9]+)/', $output, $pagecountmatches);
	$pagecount = $pagecountmatches[1];

	// find page sizes
	preg_match('/Page size:\s+([0-9]{0,5}\.?[0-9]{0,3}) x ([0-9]{0,5}\.?[0-9]{0,3})/', $output, $pagesizematches);
	$widthMm = round($pagesizematches[1]/2.83);
	$heightMm = round($pagesizematches[2]/2.83);

	echo "pagecount = $pagecount <br/>width(mm) = $widthMm<br/>height(mm) = $heightMm<br/><br/>";
	
	echo "Width in mm (1% of the width as inaccuration is allowed):" . "<br/>";
	assertAlmostEquals($expectedWidth, $widthMm, " ", $allowedInaccurateFactor * $expectedWidth);
	echo "Height in mm (1% of the height as inaccuration is allowed):" . "<br/>";
	assertAlmostEquals($expectedHeight, $heightMm, " ", $allowedInaccurateFactor * $expectedHeight);
	
	unlink($URI);
	
	function getMostRecentPdfFile($path){
		
		$latest_ctime = 0;
		$latest_filename = '';    

		$d = dir($path);
		while (false !== ($entry = $d->read())) {
		  $filepath = "{$path}/{$entry}";
		  // could do also other checks than just checking whether the entry is a file
		  $info = pathinfo($filepath);
		  if (is_file($filepath) && filectime($filepath) > $latest_ctime && isset($info["extension"]) && $info["extension"] == "pdf") {
			$latest_ctime = filectime($filepath);
			$latest_filename = $entry;
		  }
		}
		return $latest_filename;
	}
?>